<?php
/**
 * 分离数组，将一个数组按照指定字段分离为两个
 * @param $oldArray array
 * @param $field string
 * @return array
 */
function splitArray($oldArray, $field){
    $fieldArr = explode(',', $field);
    $newArray = array();
    foreach($fieldArr as $v){
        $newArray[$v] = $oldArray[$v];
        unset($oldArray[$v]);
    }
    return array($oldArray, $newArray);
}
/**
 * 获取中英混合字符串的字符长度（一个汉字2长度，一个英文字符1长度）
 * @param $str
 * @return float
 */
function getStrLength($str){
    return (strlen($str) + mb_strlen($str, 'UTF8')) / 2;
}
/**
 * 检验各类型字符串是否符合规则
 * @param        $str
 * @param int $type 1表示用户昵称，2表示团体名称/社区名称/文档名字
 * @return bool
 */
function checkStrLength($str, $type = 1){
    if($type === 1){
        return getStrLength($str) >= 4 && getStrLength($str) <= 14;
    }else if($type === 2){
        return getStrLength($str) >= 4 && getStrLength($str) <= 64;
    }else{
        return false;
    }
}
/**
 * 检测是否是使用移动端访问
 * @return bool
 */
function isMobile(){
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}
/**
 * 生成页面跳转链接
 * @param $count int 数据总数
 * @param $every int 每页展示的数据数
 * @param int $cur 当前页数
 * @param int $num 展示的页面链接数[必须为奇数]
 * @return string
 */
function page($count, $every, $cur = 1, $num = 7){
    $pages = ceil($count / $every);     // 总页面数
    if($pages <= 1){
        return '';
    }
    $baseurl = preg_replace("/(\/p\/\d+)?/i", "", rtrim(rtrim($_SERVER['REQUEST_URI'], '.html'), '/'));
    // FIRST 链接展示
    if($cur == 1){
        $first = '<span>FIRST</span>';
    }else{
        if($baseurl == ''){
            $first = '<a href="/">FIRST</a>';
        }else{
            $first = '<a href="'.$baseurl.'.html">FIRST</a>';
        }
    }
    // LAST 链接展示
    if($cur == $pages){
        $last = '<span>LAST</span>';
    }else{
        $last = '<a href="'.$baseurl.'/p/'.$pages.'.html">LAST</a>';
    }
    // 中间的链接展示
    if($pages <= $num){
        $start = 1;
        $end = $pages;
    }else{
        $mark = ceil($num / 2);
        if($cur < $mark){
            $start = 1;
        }else if($cur > ($pages - $mark)){
            $start = $pages - $num + 1;
        }else{
            $start = $cur - $mark + 1;
        }
        $end = $num;
    }
    $content = '';
    for($i = 0; $i < $end; $i++){
        if($start == 1){
            if($cur == 1){
                $content .= '<a href="javascript:void(0)" class="current">1</a>';
            }else{
                if($baseurl == ''){
                    $content .= '<a href="/">1</a>';
                }else{
                    $content .= '<a href="'.$baseurl.'.html">1</a>';
                }
            }
        }else{
            if($start == $cur){
                $content .= '<a href="javascript:void(0)" class="current">'.$start.'</a>';
            }else{
                $content .= '<a href="'.$baseurl.'/p/'.$start.'.html">'.$start.'</a>';
            }
        }
        $start ++;
    }
    return '<div class="page clearfix">'.$first.$content.$last.'</div>';
}

/**
 * 社区页面分页效果
 * @param $count
 * @param $every
 * @param int $cur
 * @param int $num
 * @return string
 */
function page2($count, $every, $cur = 1, $num = 5){
    $pages = ceil($count / $every);     // 总页面数
    if($pages <= 1){
        return '';
    }
    $baseurl = preg_replace("/(\/p\/\d+)?/i", "", rtrim(rtrim($_SERVER['REQUEST_URI'], '.html'), '/'));
    // FIRST 链接展示
    if($cur == 1){
        $first = '<span><<</span>';
    }else{
        if($baseurl == ''){
            $first = '<a href="/"><<</a>';
        }else{
            $first = '<a href="'.$baseurl.'"><<</a>';
        }
    }
    // LAST 链接展示
    if($cur == $pages){
        $last = '<span>>></span>';
    }else{
        $last = '<a href="'.$baseurl.'/p/'.$pages.'">>></a>';
    }
    // 中间的链接展示
    if($pages <= $num){
        $start = 1;
        $end = $pages;
    }else{
        $mark = ceil($num / 2);
        if($cur < $mark){
            $start = 1;
        }else if($cur > ($pages - $mark)){
            $start = $pages - $num + 1;
        }else{
            $start = $cur - $mark + 1;
        }
        $end = $num;
    }
    $content = '';
    for($i = 0; $i < $end; $i++){
        if($start == 1){
            if($cur == 1){
                $content .= '<a href="javascript:void(0)" class="active">1</a>';
            }else{
                if($baseurl == ''){
                    $content .= '<a href="/">1</a>';
                }else{
                    $content .= '<a href="'.$baseurl.'">1</a>';
                }
            }
        }else{
            if($start == $cur){
                $content .= '<a href="javascript:void(0)" class="active">'.$start.'</a>';
            }else{
                $content .= '<a href="'.$baseurl.'/p/'.$start.'">'.$start.'</a>';
            }
        }
        $start ++;
    }
    return '<div class="page clearfix">'.$first.$content.$last.'</div>';
}
/**
 * 富文本xss过滤
 * @param $html
 * @return string
 */
function filterXss($html){
    Vendor('XssHtmlFliter.kses');
    $allowedposttags = array(
        'address' => array(),
        'a' => array(
            'href' => true,
            'rel' => true,
            'rev' => true,
            'name' => true,
            'target' => true,
        ),
        'abbr' => array(),
        'acronym' => array(),
        'area' => array(
            'alt' => true,
            'coords' => true,
            'href' => true,
            'nohref' => true,
            'shape' => true,
            'target' => true,
        ),
        'article' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'aside' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'audio' => array(
            'autoplay' => true,
            'controls' => true,
            'loop' => true,
            'muted' => true,
            'preload' => true,
            'src' => true,
        ),
        'b' => array(),
        'bdo' => array(
            'dir' => true,
        ),
        'big' => array(),
        'blockquote' => array(
            'cite' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'br' => array(),
        'button' => array(
            'disabled' => true,
            'name' => true,
            'type' => true,
            'value' => true,
        ),
        'caption' => array(
            'align' => true,
        ),
        'cite' => array(
            'dir' => true,
            'lang' => true,
        ),
        'code' => array(),
        'col' => array(
            'align' => true,
            'char' => true,
            'charoff' => true,
            'span' => true,
            'dir' => true,
            'valign' => true,
            'width' => true,
        ),
        'colgroup' => array(
            'align' => true,
            'char' => true,
            'charoff' => true,
            'span' => true,
            'valign' => true,
            'width' => true,
        ),
        'del' => array(
            'datetime' => true,
        ),
        'dd' => array(),
        'dfn' => array(),
        'details' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'open' => true,
            'xml:lang' => true,
        ),
        'div' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'dl' => array(),
        'dt' => array(),
        'em' => array(),
        'fieldset' => array(),
        'figure' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'figcaption' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'font' => array(
            'color' => true,
            'face' => true,
            'size' => true,
        ),
        'footer' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'form' => array(
            'action' => true,
            'accept' => true,
            'accept-charset' => true,
            'enctype' => true,
            'method' => true,
            'name' => true,
            'target' => true,
        ),
        'h1' => array(
            'align' => true,
        ),
        'h2' => array(
            'align' => true,
        ),
        'h3' => array(
            'align' => true,
        ),
        'h4' => array(
            'align' => true,
        ),
        'h5' => array(
            'align' => true,
        ),
        'h6' => array(
            'align' => true,
        ),
        'header' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'hgroup' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'hr' => array(
            'align' => true,
            'noshade' => true,
            'size' => true,
            'width' => true,
        ),
        'i' => array(),
        'img' => array(
            'alt' => true,
            'align' => true,
            'border' => true,
            'height' => true,
            'hspace' => true,
            'longdesc' => true,
            'vspace' => true,
            'src' => true,
            'usemap' => true,
            'width' => true,
        ),
        'ins' => array(
            'datetime' => true,
            'cite' => true,
        ),
        'kbd' => array(),
        'label' => array(
            'for' => true,
        ),
        'legend' => array(
            'align' => true,
        ),
        'li' => array(
            'align' => true,
            'value' => true,
        ),
        'map' => array(
            'name' => true,
        ),
        'mark' => array(),
        'menu' => array(
            'type' => true,
        ),
        'nav' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'p' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'pre' => array(
            'width' => true,
        ),
        'q' => array(
            'cite' => true,
        ),
        's' => array(),
        'samp' => array(),
        'span' => array(
            'dir' => true,
            'align' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'section' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'small' => array(),
        'strike' => array(),
        'strong' => array(),
        'sub' => array(),
        'summary' => array(
            'align' => true,
            'dir' => true,
            'lang' => true,
            'xml:lang' => true,
        ),
        'sup' => array(),
        'table' => array(
            'align' => true,
            'bgcolor' => true,
            'border' => true,
            'cellpadding' => true,
            'cellspacing' => true,
            'dir' => true,
            'rules' => true,
            'summary' => true,
            'width' => true,
        ),
        'tbody' => array(
            'align' => true,
            'char' => true,
            'charoff' => true,
            'valign' => true,
        ),
        'td' => array(
            'abbr' => true,
            'align' => true,
            'axis' => true,
            'bgcolor' => true,
            'char' => true,
            'charoff' => true,
            'colspan' => true,
            'dir' => true,
            'headers' => true,
            'height' => true,
            'nowrap' => true,
            'rowspan' => true,
            'scope' => true,
            'valign' => true,
            'width' => true,
        ),
        'textarea' => array(
            'cols' => true,
            'rows' => true,
            'disabled' => true,
            'name' => true,
            'readonly' => true,
        ),
        'tfoot' => array(
            'align' => true,
            'char' => true,
            'charoff' => true,
            'valign' => true,
        ),
        'th' => array(
            'abbr' => true,
            'align' => true,
            'axis' => true,
            'bgcolor' => true,
            'char' => true,
            'charoff' => true,
            'colspan' => true,
            'headers' => true,
            'height' => true,
            'nowrap' => true,
            'rowspan' => true,
            'scope' => true,
            'valign' => true,
            'width' => true,
        ),
        'thead' => array(
            'align' => true,
            'char' => true,
            'charoff' => true,
            'valign' => true,
        ),
        'title' => array(),
        'tr' => array(
            'align' => true,
            'bgcolor' => true,
            'char' => true,
            'charoff' => true,
            'valign' => true,
        ),
        'track' => array(
            'default' => true,
            'kind' => true,
            'label' => true,
            'src' => true,
            'srclang' => true,
        ),
        'tt' => array(),
        'u' => array(),
        'ul' => array(
            'type' => true,
        ),
        'ol' => array(
            'start' => true,
            'type' => true,
            'reversed' => true,
        ),
        'var' => array(),
        'video' => array(
            'autoplay' => true,
            'controls' => true,
            'height' => true,
            'loop' => true,
            'muted' => true,
            'poster' => true,
            'preload' => true,
            'src' => true,
            'width' => true,
        ),
    );
    return wp_kses($html, $allowedposttags);
}
/**
 * 生成二维码
 * @param $url
 * @param $file
 * @param $level
 * @param $size
 */
function getPng($url, $file, $level, $size){
    Vendor('QrCode.qrCode');
    return QRcode::png($url, $file, $level, $size);
}
/**
 * PHP上传文件到七牛云服务器
 * @param $file
 * @param $key
 * @return bool
 */
function updateQiniu($file, $key){
    Vendor('Qiniu.autoload');
    $accessKey = C('QINIU_AK');
    $secretKey = C('QINIU_SK');
    // 构建鉴权对象
    $auth = new \Qiniu\Auth($accessKey, $secretKey);
    // 要上传的空间
    $bucket = 'imgs';
    // 生成上传 Token
    $token = $auth->uploadToken($bucket);
    // 初始化 UploadManager 对象并进行文件的上传。
    $uploadMgr = new \Qiniu\Storage\UploadManager();
    // 调用 UploadManager 的 putFile 方法进行文件的上传。
    $result = $uploadMgr->putFile($token, $key, $file);
    return is_null($result[1]);
}
/**
 * 七牛 的一个加密算法
 * @param $data string
 * @return mixed string
 */
function base64_urlSafeEncode($data){
    $find = array('+', '/');
    $replace = array('-', '_');
    return str_replace($find, $replace, base64_encode($data));
}
function qiniu(){
    $put = C('QINIU_UPLOAD_CONFIG');
    $put['deadline'] = time() + 36000;
    $ak = C('QINIU_AK');
    $sk = C('QINIU_SK');
    $putPolicy = json_encode($put);
    $encodedPutPolicy = base64_urlSafeEncode($putPolicy);
    $sign = hash_hmac('sha1', $encodedPutPolicy, $sk, true);
    $encodedSign = base64_urlSafeEncode($sign);
    return $ak.':'.$encodedSign.':'.$encodedPutPolicy;
}
/**
 * 格式化时间
 * @param $time
 * @return string
 */
function formatTime($time){
    $value = time() - $time;
    if ($value < 0) {
        return '0';
    } else if ($value < 60) {
        return $value.'秒前';
    } else if ($value < 3600) {
        return (int)($value / 60).' 分钟前';
    } else if ($value < 86400) {
        return (int)($value / 3600).' 小时前';
    } else if ($value < 2592000) {
        return (int)($value / 86400).' 天前';
    } else if ($value < 31104000) {
        return (int)($value / 2592000).' 个月前';
    } else {
        return (int)($value / 31104000).' 年前';
    }
}
/**
 * 格式化次数
 * @param $count
 * @return string
 */
function formatCount($count){
    if ($count < 0) {
        return '0';
    } else if ($count < 1000) {
        return $count;
    } else {
        return (int)($count/1000).'k';
    }
}








/**
 * 检测字符串长度,一个汉字代表一个长度
 * @param $str string 被检测的字符串
 * @return int 字符串的长度
 */
function lengthCheck($str){
    preg_match_all('/./us', $str, $match);
    return count($match[0]);
}


/**
 * 邮件发送函数
 * @param $to string 发送到那个邮件
 * @param $subject string 邮件标题
 * @param $content string 邮件内容
 * @param string $account 发送邮件的账户
 * @return bool 
 * @throws phpmailerException
 */
function sendMail($to, $subject, $content, $account = 'ACCOUNT') {
    Vendor('PHPMailer.PHPMailerAutoload');     
    $mail = new PHPMailer(); //实例化
    $username = C('MAIL_'.$account);
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
    $mail->SMTPAuth = true; //启用smtp认证
    $mail->Username = $username; //你的邮箱名
    $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
    $mail->From = $username; //发件人地址（也就是你的邮箱地址）
    $mail->FromName = '二网[Second.v.n]'; //发件人姓名
    $mail->AddAddress($to,"");
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(true); // 是否HTML格式邮件
    $mail->CharSet='utf-8'; //设置邮件编码
    $mail->Subject =$subject; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = ""; //邮件正文不支持HTML的备用显示
    return($mail->Send());
}
// function filterXss($html){
//     Vendor('XssHtmlFliter.Xsshtmlfliter');
//     $xss = new XssHtml($html);
//     return $xss->getHtml();
// }

/**
 * Ajax 通信接口封装
 * @param  int $code    状态码
 * @param  string  $msg 提示消息
 * @param  array   $data    数据
 * @return string           json字符串
 */
function json($code = 200, $msg = "", $data = array()){
    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    echo json_encode($result);
    exit;
}





// 加密SimpleJWT
function encodeSimpleJwt($data){
    $dataStr = urlsafeB64Encode(json_encode($data));
    $md5 = md5(md5($dataStr.C('SIMPLEJWT_CODE')).C('SIMPLEJWT_SECOND_CODE'));
    return $dataStr.'.'.$md5;
}
// 解析SimpleJWT
function decodeSimpleJwt($token){
    list($dataStr, $md5) = explode('.', $token);
    if($md5 !== md5(md5($dataStr.C('SIMPLEJWT_CODE')).C('SIMPLEJWT_SECOND_CODE'))){
        return false;
    }
    $data = json_decode(urlsafeB64Decode($dataStr), true);
    return is_array($data) ? $data : false;
}
// 安全加密/解析BASE64编码
function urlsafeB64Decode($input){
    $remainder = strlen($input) % 4;
    if ($remainder) {
        $padlen = 4 - $remainder;
        $input .= str_repeat('=', $padlen);
    }
    return base64_decode(strtr($input, '-_', '+/'));
}
function urlsafeB64Encode($input){
    return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}

















/**
 * 检测用户是否登录,根据SESSION来判断
 * @return int 0-未登录，大于0-当前登录用户ID；
 */
function checkLogin(){
    $uid = session('uid');
    return empty($uid) ? 0 : (int)$uid;
}

/**
 * 设置Cookie中的token，用以判断用户是否登录
 * @param $str string 基本的字符串
 * @return string 加盐后的token字符串
 */
function setAutoToken($str){
    return '' === $str ? '' : md5(sha1($str.'wooowang').'autoLogin');
}

/**
 * 生成验证邮箱的token值
 * @param $id int 用户ID
 * @param $email string 用户邮箱
 * @return string 经过加盐处理后的token值
 */
function authEmailToken($id, $email){
    return md5(md5($id.$email."second").'network');
}

/**
 * 生成重置密码的token值
 * @param $id int 用户ID
 * @param $password string 密码的MD5
 * @return string 加盐处理后的token值
 */
function resetPasswordToken($id,$password){
    return md5(md5($id.'_wooo_wang_'.$password).'_great');
}

/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 */
function passwordMd5($str){
    return '' === $str ? '' : md5(md5($str.'heheda').'rilegou');
}
